import axios from "axios";
import { ElMessage } from "element-plus";
import { useStore } from "@/store";

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 60000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    let store = useStore();
    let token = store.userInfo?.token;
    if (token) {
      config.headers["token"] = token;
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (response.status == 200) {
      if (response.headers["content-type"] == "application/json") {
        if (res.code !== 200) {
          ElMessage({
            message: res.message || "Error",
            type: "error",
            duration: 5 * 1000,
          });
          return Promise.reject(new Error(res.message || "Error"));
        } else {
          return res;
        }
      } else {
        const headers = response.headers;
        const contentType = headers["content-type"];
        const blob = new Blob([response.data], { type: contentType });
        const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(headers["content-disposition"]);
        let fileName;
        if (matches != null && matches[1]) {
          fileName = matches[1].replace(/['"]/g, "");
        } else {
          return Promise.reject(new Error("content-disposition content error"));
        }
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = fileName; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        return;
      }
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error);
    ElMessage({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
